package com.shuyuwl.controller;

import com.shuyuwl.domain.File;
import com.shuyuwl.service.FileService;
import com.shuyuwl.utils.FastFileUploadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author: Tangnibal
 * @date: 2019年11月11日
 */
@Controller
@RequestMapping("/file")
@Api(tags = "文件下载")
@Slf4j
@CrossOrigin(allowCredentials = "true",maxAge = 3600,allowedHeaders = "*",origins = "*")
public class FileDownloadController {

    @Autowired
    private FileService service;
    @ApiOperation(value = "下载文件")
    @GetMapping("/download/{id}")
    public void download(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws Exception {
        File file = service.getById(id);

        String path = file.getPath();
        java.io.File attachFile = FastFileUploadUtil.fastDfsDownload(path);
        if (!attachFile.exists()){
            log.error("文件不存在!");
            return;
        }

        // 文件名编码处理
        String filename = file.getFilename();
        //获得浏览器信息并转换为大写
        String agent = request.getHeader("User-Agent").toUpperCase();
        //IE浏览器和Edge浏览器
        if (agent.indexOf("MSIE") > 0 || agent.indexOf("GECKO")>0) {
            filename = URLEncoder.encode(filename, "utf-8");
        } else {  //其他浏览器
            filename = new String(filename.getBytes("ISO8859-1"), "UTF-8");
        }

        response.reset();
        response.setContentType("application/x-msdownload");
        response.setHeader("Content-Type", "application/octet-stream");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-disposition", "attachment;filename=" + filename);

        ServletOutputStream os = null;
        BufferedInputStream bis = null;
        try {
            os = response.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(attachFile));
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = bis.read(buffer)) !=-1){
                os.write(buffer, 0, len);
            }
            os.flush();
        } catch (IOException e) {
            log.error("文件下载出现错误：{}", e.getMessage());
        } finally {
            try {
                if (attachFile.exists()){
                    attachFile.delete();
                }
                os.close();
                bis.close();
            } catch (IOException e) {
                log.error("关闭输入输出流出现错误：{}", e.getMessage());
            }
        }
    }
}
